<template>
	<el-card>
		<template #header>
			<el-space wrap>
				<el-input style="width:100%;" v-model="deptFilterText" placeholder="编号、名称过滤" auto-complete="off" />
				<el-button type="primary" @click="addTopNode" icon="plus" title="添加一级部门" />
				<el-button v-if="showConfirm" type="warning" @click="confirm" icon="check" title="确认选择" />

			</el-space>
		</template>
		<el-tree v-if="treeVisible" v-loading="listLoading" :props="defaultDeptTreeProps" :filter-node-method="filterDeptNode"
			:show-checkbox="showCheckbox" :expand-on-click-node="expandOnClickNode" :indent="indent" :node-key="'deptid'"
			:default-expanded-keys="defaultExpandedKeys" :default-checked-keys="defaultCheckedKeys" auto-expand-parent
			highlight-current style="min-height:100px;" @check-change="handleCheckChange" @current-change="handleCurrentChange"
			@node-click="handleNodeClick" :check-on-click-node="true" check-strictly lazy :load="loadNode" ref="deptTree"  @contextmenu.prevent >

			<template #default="{ node, data }">
				<div class="custom-tree-node" @contextmenu.prevent title="右键可以增删改">
					<el-popover :open-delay="1000" placement="top-start" :width="showConfirm ? 300 : 200" trigger="contextmenu">

						<el-button icon="plus" circle type="success" v-if="!(!data.deptid || data.deptid == 'A0' || data.deptid == '0')"
							@click.prevent.stop="addNode(data, node)" title="添加子部门" />
						<el-button icon="edit" circle type="warning" v-if="!(!data.deptid || data.deptid == 'A0' || data.deptid == '0')"
							@click.prevent.stop="editNode(data, node)" title="修改部门" />
						<el-button icon="delete" circle type="danger" v-if="!(!data.deptid || data.deptid == 'A0' || data.deptid == '0')"
							@click.prevent.stop="deleteNode(data, node)" title="删除该部门" />

						<template #reference>
							<div style="display:flex;align-items:center;width:100%;"> {{ data.deptName }} </div>
						</template>
					</el-popover>
				</div>
			</template>
		</el-tree>
	</el-card>

	<mdp-dialog title="新增部门" ref="addDialog" width="60%" append-to-body>
		<el-form ref="addDept" :model="addDept" label-width="200">

			<el-form-item label="上级部门">

				<el-tag>{{ currentDept && currentDept.deptid && currentDept.deptid != 'A0' ? currentDept.deptName : "顶级部门A0" }}</el-tag>

			</el-form-item>
			<el-form-item label="部门编号">
				<el-input v-model="addDept.deptid" placeholder="如果为空，则系统自动生成" />
			</el-form-item>
			<el-form-item label="部门名称" prop="deptName" :rules="[
				{ required: true, message: '名称不能为空' }
			]">
				<el-input v-model="addDept.deptName" />
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="$refs['addDialog'].close()">关闭</el-button>
			<el-button type="primary" v-loading="addLoading" @click="addDeptSubmit">确 定</el-button>
		</template>
	</mdp-dialog>

	<mdp-dialog title="修改部门提示"   width="60%" append-to-body ref="editDialog"> 
			<el-form ref="editDept" :model="editDept" label-width="200">
				<el-form-item label="部门编号" prop="id">
					{{ editDept.deptid }}
				</el-form-item>
				<el-form-item label="部门名称" prop="deptName" :rules="[
					{ required: true, message: '名称不能为空' }
				]">
					<el-input v-model="editDept.deptName" />
				</el-form-item>

			</el-form> 
		<template #footer>
			<el-button @click="$refs['editDialog'].close()">关 闭</el-button>
			<el-button type="primary" v-loading="editLoading" @click="editDeptSubmit">确 定</el-button>
		</template>
	</mdp-dialog>
</template>
  
<script>
import { mapState } from 'pinia'
import { useUserStore } from '@/store/modules/user'

export default {
	watch: {
		deptFilterText(val) {
			this.$refs.deptTree.filter(val);
		},
		checkedKeys(val) {
			this.$refs.deptTree.setCheckedKeys(val);
		},
		refresh(val) {
			this.getDeptTreeData(val);
		},
		currentKey(val) {
			this.$refs.deptTree.setCheckedKeys([val]);
		},
		value(val) {
			this.deptid = val;
		},
		deptid(val) {
			this.$emit('input', val);
		},
	},
	components: {
	},
	computed: {
		defaultExpandedKeys() {
			return this.expandRowKeys
		},
		defaultCheckedKeys() {
			if (this.value) {
				return [this.value];
			}
			return this.checkedKeys;
		},
		...mapState(useUserStore, [
			'userInfo'
		]), 
	},
	props: {
		'value': String, Array,
		'branchId': String,
		'visible': { type: Boolean, default: false },
		'showCount': { type: Boolean, default: false },
		'showRoot': { type: Boolean, default: false },
		'countTips': String,
		'showFilter': { type: Boolean, default: false },
		'multiple': { type: Boolean, default: false },
		'checkedKeys': Array,
		'refresh': { type: Boolean, default: false },
		'defaultExpandAll': { type: Boolean, default: false },
		'expandOnClickNode': { type: Boolean, default: false },
		showCheckbox: { type: Boolean, default: false },
		showConfirm: { type: Boolean, default: false },
		'indent': Number

	},
	data() {
		return {
			deptFilterText: '', 
			defaultDeptTreeProps: { 
				id: 'deptid',
				label: 'deptName',
				children: 'children',
				isLeaf: function (n) {
					return n.childNum <= 0
				}
			},
			listLoading: false,
			deptid: '',  
			expandRowKeys: [],
			root: null,
			resolve: null,

			addDept:{deptid:'',deptName:'',pdeptid:''},
			editDept:{deptid:'',deptName:'',pdeptid:''},
			treeVisible:true,
			isAddTop: false,
			currentDept:{},
		}
	},
	methods: {
		addDeptSubmit(){
				var branchId=this.userInfo.branchId
				var pdeptid=""
				if(this.isAddTop){
					pdeptid="A0"
				}else{
					pdeptid=this.currentDept.deptid
					branchId=this.currentDept.branchId||this.userInfo.branchId
				}
				this.addDept.pdeptid=pdeptid 
				this.addDept.branchId=branchId  
				this.$refs.addDept.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							this.$mdp.addDept(this.addDept).then(res=>{
								this.addLoading=false;
								if(res.tips.isOk){
									

									this.$message.success(res.tips.msg); 
									if(!this.isAddTop){
										if(this.currentDept.children){
											this.currentDept.children.push(res.data)
										}else{
											this.currentDept.children=[res.data]
										}
									}else{
										this.$refs['deptTree'].append(res.data,this.root)
									} 
								}else{
									this.$message.error(res.tips.msg);
								}
							}).catch(e=>this.addLoading = false  );

						});
					}
				});

			},

			editDeptSubmit(){
				this.$refs.editDept.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							this.$mdp.editDept(this.editDept).then(res=>{
								//console.log("res--"+JSON.stringify(res));
								this.editLoading = false;
								if(res.tips.isOk){ 
									this.$message.success(res.tips.msg); 
									
									this.$refs['deptTree'].updateKeyChildren(res.data.deptid,res.data)
									this.editVisible=false
								}else{
									this.$message.error(res.tips.msg);
								}
							}).catch(e=>this.editLoading = false  );

						});
					}
				});

			},
			addTopNode(){
				this.isAddTop=true  
				this.addDept.pdeptid='A0'
				this.addDept.deptid=''
				this.addDept.deptName=''
				this.$refs['addDialog'].open()
			},
		    addNode(data, node, comp) {
					this.isAddTop=false
				this.currentDept=data   
				
				this.addDept.pdeptid=data.deptid
				this.addDept.deptid=''
				this.addDept.deptName=''
				this.$refs['addDialog'].open()
			},
		    editNode(data, node, comp) {
				this.editDept=data  
				this.$refs['editDialog'].open()
		    },
		    deleteNode(data, node, comp) { 
						if(data.childNum>0||data.children?.length>0){
							this.$message.error("请先删除子元素");
							return;
						}
						let params={
							deptid:data.deptid
						} 
						this.$confirm('确认删除吗？', '提示', {}).then(() => {
							this.$mdp.delDept(params).then(res=>{
								//console.log("res--"+JSON.stringify(res));
								if(res.tips.isOk){ 
									this.$refs['deptTree'].remove(data)
									this.$message.success(res.tips.msg); 
								}else{
									this.$message.error(res.tips.msg);
								}
							});
						})
					return false;
		    },
		handleCheckChange(data, checked, indeterminate) {
			let checkedKeys = this.$refs.deptTree.getCheckedKeys();

			if (this.multiple === undefined || this.multiple === false || this.multiple === 'false') {
				if (checked == true) {
					if (checkedKeys.length > 1) {
						this.$refs.deptTree.setCheckedKeys([data['deptid']]);
						this.$emit('check-change', data, checked, indeterminate);
						this.deptid = data['deptid'];
					} else {
						this.$emit('check-change', data, checked, indeterminate);
						this.deptid = data['deptid'];
					}
				} else {
					if (checkedKeys.length == 0) {
						this.deptid = '';
						this.$emit('check-change', data, checked, indeterminate);
					}
				}
			} else {
				this.$emit('check-change', data, checked, indeterminate);
			}
		},
		handleCurrentChange(data, node) {
			this.$emit('current-change', data, node);
		},
		handleNodeClick(data, node, comp) {
			this.$emit('node-click', data, node, comp);
		}, 
		translateDataToTree(data) {
			if (!data) {
				return [];
			}
			return data
		},
		//获取部门树列表
		getDeptTreeData(refresh) {
			this.treeVisible=false
			this.$nextTick(()=>{
				this.treeVisible=true
			})
		},
		filterDeptNode(value, data) {
			if (!value) return true;
			if (data.deptid.indexOf(value) >= 0 || data.deptName.indexOf(value) >= 0) {
				return true;
			} else {
				if (data.pdeptid && data.pdeptid.indexOf(value) >= 0) {
					return true;
				}
			}
			return false;
		}, 
		confirm() {
			var nodes = this.$refs.deptTree.getCheckedNodes(false, false)
			if (this.multiple) {
				this.$emit('confirm', nodes)
			} else {
				this.$emit('confirm', nodes && nodes.length > 0 ? nodes[0] : null)
			}

		},
		loadNode(node, resolve) {
			if (node.level === 0) {
				this.root = node
				this.resolve = resolve
				let params = {
					'res.levelType': 'L1'
				};
				params.branchId = this.branchId 
				if (params.branchId == null || params.branchId == '') {
					params.branchId = this.userInfo.branchId
				} 
				this.listLoading = true;
				this.$mdp.listDept(params).then((res) => {
					var tips = res.tips;
					var data = res.data;
					this.listLoading = false;
					var tempData = this.translateDataToTree(data);
					this.expandRowKeys = tempData?.length > 0 ? [tempData[0]] : []
					resolve(tempData)

				}).catch(() => {
					this.listLoading = false;
				});
			} else {
				setTimeout(() => {
					let params = {
						pdeptid: node.data.deptid
					}; 
					if (params.branchId == null || params.branchId == '') {
						params.branchId = this.userInfo.branchId
					}
					this.listLoading = true;
					this.$mdp.listDept(params).then((res) => {
						var tips = res.tips;
						var data = res.data;
						this.listLoading = false;
						resolve(this.translateDataToTree(data))

					}).catch(() => {
						this.listLoading = false;
					});
				}, 500);

			}
		}
	},
	mounted() {
		this.deptid = this.value;
		//this.getDeptTreeData();
	}
}

</script>
  
<style scoped> 
</style>
  